'use strict';
const  path =  require('path');
const  fs =  require('fs');
const util = require('../util/util') 
const Controller = require('./base');
const awaitWriteStream = require('await-stream-ready').write
const sendToWormhole = require('stream-wormhole')

/**
 * @controller Test
 */
 class TestController extends Controller {
  /**
  * @summary Test 
  * @description 物件列表
  * @router GET /test/list
  * @Request query  interger page 页码 eg:1    
  * @Request query interger pageSize 页长 eg:10
  * @consumes html/text applicatoin/json
  * @response 200 list
  */  
  async list() {
    const { ctx } = this; 
    let { page,pageSize } = util.args(this.ctx);  
    page = page ? page : 1 ; pageSize = pageSize ? pageSize : 10;
    const data = await this.app.mysql.select("app",{ limit: pageSize , offset:(page-1) * pageSize, })
    this.success(data)
  }

  /**
  * @summary Test 
  * @description 物件详细
  * @router GET /test/item
  * @Request query  interger id ID eg:1     
  * @consumes html/text applicatoin/json
  * @response 200 user
  */   
  async item() { 

     const data = await this.app.mysql.select("app",{  where:{id: 30 },})
     this.success(data)
 
  }

  /**
  * @summary Test 
  * @description 图片
  * @router GET /test/upload
  * @Request query interger id ID eg:1     
  * @consumes html/text applicatoin/json
  * @response 200 user
  */   
  async upload1() { 
      const stream = await this.ctx.getFileStream();  
      const filename = Math.random().toString(36).substr(2) + new Date().getTime() + path.extname(stream.filename).toLocaleLowerCase();
      const target = path.join(this.config.baseDir,'app/public/upload',filename);
      const writeStream = fs.createWriteStream(target); 
      let avatar = '';
      try { 
        await awaitWriteStream(stream.pipe(writeStream)); // 异步把文件流 写入
        avatar = "http://" + this.app.config.cluster.listen.hostname + ':' + this.app.config.cluster.listen.port + this.config.static.prefix + 'upload/' + filename;
        console.log(this.config.static.prefix)
        console.log(avatar)
    } catch (err) { 
        await sendToWormhole(stream); // 如果出现错误，则关闭管道
        this.ctx.status = 500;
        this.ctx.body = { msg: '未知错误！' }
        throw err;
    }
    this.ctx.status = 200; 
    this.ctx.body = { msg: '上传成功！', avatar } 
 
  }

  async upload() {  // 上传外围服务器的方式 
    const FormData = require('form-data')
    const request = require('request');
    const stream = await this.ctx.getFileStream();  
    const form  = new FormData();
    form.append('file', stream); 
   
   try { 
       request.post({
        url: "http://47.115.81.68:8079/user/uploadFile/externalUpload/33B13123708940F5CBDD3C1030E2F865",
        headers: {
          'Content-Type': 'multipart/form-data', 
        },
        formData: {
          files: form // 
        },
      }, function(err, resp, data) { 
        console.log(resp);
        console.log(data);
      }); 
      this.ctx.status = 200; 
      this.ctx.body = { msg: '上传成功！' } 
      
    } catch (err) { 
        await sendToWormhole(stream); // 如果出现错误，则关闭管道
        this.ctx.status = 500;
        this.ctx.body = { msg: '未知错误！' }
        throw err;
    } 
  }
  
}
module.exports =  TestController

/*
上传文件的业务 
零时的文件 定时清除
永久的文件维护  /upload/user/ 
*/
 
